<template>
  <div class="app-container customer-div">
    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="订单日期：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.createTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="杂费(装卸费)付款时间：" label-width="140px">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.consultationPayTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否已付款：">
          <el-select v-model="listQuery.consultationPayState" class="input-width" style="width:100px" placeholder="请选择" clearable>
            <el-option :value="1" label="是" :key="1"></el-option>
            <el-option :value="0" label="否" :key="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单号：">
          <el-input v-model="listQuery.orderSn"></el-input>
        </el-form-item>
        <el-form-item label="客户名称：">
          <el-autocomplete
                  clearable
                  class="inline-input"
                  value-key="customerName"
                  :fetch-suggestions="querySearch"
                  v-model="listQuery.customerName"
                  placeholder="请输入内容"
                  @select="handleSelectCustomerName"
                  :trigger-on-focus="false"
                  style="width: 270px;"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="业务员：">
          <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
                  v-if="consultationListExport"
                  @click="downloadExcel()"
                  type="primary">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
      <!--数据列表-->
      <div class="table-container">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          border
          style="width: 100%; margin-top: 20px">
          <el-table-column  label="订单号" width="140" align="center" prop="orderSn">
            <template slot-scope="scope">
              <div>
                {{scope.row.orderSn}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="客户名称"
            width="300">
            <template slot-scope="scope">
                {{scope.row.customerName}}
            </template>
          </el-table-column>
          <el-table-column
                  label="合同时间"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.createTime}}
            </template>
          </el-table-column>
          <el-table-column
            prop="fromCompany"
            align="center"
            label="合同公司"
            width="100">
          </el-table-column>
          <el-table-column
            align="center"
            width="150"
            label="品名">
            <template slot-scope="scope">
                {{scope.row.goodsName}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  width="150"
                  label="牌号">
              <template slot-scope="scope">
                {{scope.row.goodsSn}}
              </template>
          </el-table-column>
          <el-table-column
            label="合同数量"
            width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.goodsNum}}
            </template>
          </el-table-column>
          <el-table-column
                  label="已发货数量"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.goodsSendNum}}
            </template>
          </el-table-column>
          <el-table-column
                  label="合同价格"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.goodsPrice}}
            </template>
          </el-table-column>
          <el-table-column
            label="合同总金额"
            width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.orderAmount}}
            </template>
          </el-table-column>
          <el-table-column
            label="订单收款金额"
            width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.paidAmount}}
            </template>
          </el-table-column>
          <el-table-column
                  label="业务员"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.userName}}
            </template>
          </el-table-column>
          <el-table-column
                  label="杂费(装卸费)"
                  width="120"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.consultation}}
            </template>
          </el-table-column>
          <el-table-column
                  label="是否已付款"
                  width="120"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.consultationPayState}}
            </template>
          </el-table-column>
          <el-table-column
                  label="付款时间"
                  width="120"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.consultationPayTime}}
            </template>
          </el-table-column>
          <el-table-column
                  label="付款操作人"
                  width="120"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.consultationPayUser}}
            </template>
          </el-table-column>
          <el-table-column
                  label="付款金额"
                  width="120"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.consultationPayAmount}}
            </template>
          </el-table-column>
          <el-table-column
                  label="付款备注"
                  width="120"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.consultationPayRemark}}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            width="80"
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button
                  v-if="scope.row.consultationPayState == '否'"
                  type="text"
                  size="mini"
                  @click="showDialog(scope.row)">确认付款
              </el-button>
              <el-button
                      v-if="scope.row.consultationPayState == '是'"
                      type="text"
                      size="mini"
                      @click="showDialog(scope.row)">修改
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>
    <!--确认付款-->
    <el-dialog
            :close-on-click-modal="false"
            :beforeClose="handleClose"
            title="确认付款"
            :visible.sync="dialogVisible"
            width="600px">
      <el-form :model="priceForm" size="mini" label-width="90px"  ref="priceForm" :rules="rules">
          <el-form-item label="订单单号：" >
              {{priceForm.orderSn}}
          </el-form-item>
        <el-form-item label="杂费(装卸费)：">
              {{priceForm.consultation}}
        </el-form-item>
        <el-form-item label="报销金额："  prop="consultationPayAmount">
          <el-input v-model="priceForm.consultationPayAmount" style="width:150px"></el-input>
        </el-form-item>
        <el-form-item label="报销备注：" prop="consultationPayRemark">
            <el-input v-model="priceForm.consultationPayRemark" style="width:450px" type="textarea" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {getCustomerOption,getOrderUsersList,postOrderPay,invoicesList,invoicesEnter,consultationList,consultationPay} from '@/api/partner'
  import {validateCommission} from '@/utils/validate';
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    const defaultListQuery={
      "createTime" :     null, //订单时间
      "consultationPayTime" :     null, //杂费(装卸费)付款时间
      "consultationPayState" :     null, //杂费(装卸费)付款状态
      "orderSn"    :      "",   //订单号
      "userId"     :      null,  //业务员Id
      "customerName" :    "", //客户名称
      "pageNum"      :    1,  //第几页
      "pageSize"     :    10, //每页几条
    };
    const defaultPriceForm={
      ogId:'',
      orderSn : '',
      consultation:'',
      consultationPayAmount : '',
      consultationPayRemark : ""
    };
    export default {
      name: "index",
      data(){
        const isvalidateCommission = (rule, value, callback) => {
          if (!validateCommission(parseFloat(value))) {
            callback(new Error('非负整数或小数'))
          } else if(value <= 0){
            callback(new Error('请输入大于零的数'))
          }else {
            callback()
          }
        };
          return {
              listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
              tableData: [],
              count: 0,
              listLoading: false,
              userOptionList:[],
              roles:store.getters.roles ? store.getters.roles : [],
              dialogVisible:false,
              priceForm:JSON.parse(JSON.stringify(defaultPriceForm)),
              btnLoading : false,
              upUrl:'',
              rules:{
                consultationPayAmount:[{required: true, trigger: 'blur' ,validator: isvalidateCommission}],
                consultationPayRemark:[{ required: true, message: '此项必填', trigger: 'blur' }]
              },
          }
      },
      computed: {
        ...mapGetters([
          'name',
          'mobile',
          'userId'
        ]),
        isCanCustomerByAll(){
          if(this.roles.indexOf("customerByAll") != -1){
            return true
          }else{
            return false
          }
        },
        consultationListExport(){
          if(this.roles.indexOf("consultationListExport") != -1){
            return true
          }else{
            return false
          }
        },
      },
      created() {
        this.getList();
        this.getUserOptionList();
      },
      filters: {
        formatCreateTime(time) {
          if(time){
            let date = new Date(time);
            return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
          }else{
            return '--'
          }
        },
      },
      methods:{
        //下载excle
        downloadExcel(){
          let params = JSON.parse(JSON.stringify(this.listQuery));
          params.export = 1;
          consultationList(params).then((res)=>{
            require.ensure([], () => {
              const { export_json_to_excel } = require('sheet/Export2Excel');
              const tHeader = res.title;
              const filterVal = res.columns;
              const list = res.list;
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, res.fileName);
            })
          })
        },

        //下载表格数据格式化
        formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => v[j]))
        },
        //显示确认开票弹窗
        showDialog(item){
            this.dialogVisible = true;
            this.priceForm = JSON.parse(JSON.stringify(defaultPriceForm));
            this.priceForm.ogId = item.ogId;
            this.priceForm.orderSn = item.orderSn;
            this.priceForm.consultation = item.consultation;
            this.priceForm.consultationPayAmount = item.consultationPayAmount;
            this.priceForm.consultationPayRemark = item.consultationPayRemark;
        },

        //关闭确认付款弹窗
        handleClose(){
          this.$refs.priceForm.clearValidate();
          this.dialogVisible = false;
        },

        //提交确认付款
        handleConfirm(){
          this.$refs['priceForm'].validate((valid) => {
            if (valid) {
              this.btnLoading = true;
              consultationPay(this.priceForm).then(()=>{
                this.btnLoading = false;
                this.dialogVisible = false;
                this.getList()
              }).catch(()=>{
                this.btnLoading = false;
              })
            }
          })
        },

          //获取员工下拉选项
          getUserOptionList(){
            getOrderUsersList().then((res)=>{
                  this.userOptionList = res;
              })
          },

          //选择员工名称
          handleSelectUserName(key,item){
              this.listQuery[key] = item.userId;
          },

          //客户名称输入匹配
          querySearch(queryString, cb){
              getCustomerOption({keywords:queryString}).then((res)=>{
                  cb(res);
              })
          },

          //选择客户名称
          handleSelectCustomerName(item){
              this.listQuery.customerName = item.customerName
          },

        handleSizeChange(val){
          this.listQuery.pageNum = 1;
          this.listQuery.pageSize = val;
          this.getList();
        },
        handleCurrentChange(val){
          this.listQuery.pageNum = val;
          this.getList();
        },

        handleSearchList(){
          this.listQuery.pageNum = 1;
          this.getList();
        },

        //获取列表
        getList() {
          this.listLoading = true;
          consultationList(this.listQuery).then(response => {
            this.tableData = response.list;
            this.count = response.count;
            this.listLoading = false;
          }).catch(()=>{
            this.listLoading = false;
          });
        },

      },
    }
</script>

<style lang="scss">

</style>
